import datetime
import uuid
import time
from django.views import View
from django.views.static import serve
import os
import random
from django.core.cache import cache
import logging

from src.settings.pro import STATIC_ROOT, MEDIA_ROOT
from src.utils import wx
from src.settings.pro import SESSION_COOKIE_AGE
from src.utils.makeJwt import jwt_encode
from src.utils.ReturnStatus import ResponseStatus
from common.models import TbMiniappUser
from common.serializer import UserSerializers, UserInfoSerializers
from common.tool.userTool import checkPassword
from src.utils import requests
from src.utils.record import director

errlog = logging.getLogger("err")


# Create your views here.

# Create your views here.
def common_login(request):
    """
    用户名密码登录
    """
    # 接收参数
    # --- start ---
    data = eval(request.body.decode())
    username = data.get("username")
    password = "wechat"
    # --- end ---
    # 验证用户是否存在
    # --- start ---
    try:
        user = TbMiniappUser.objects.get(username=username)
    except TbMiniappUser.DoesNotExist:
        user_info = {
            "uid": uuid.uuid1().hex,
            "username": username,
            "password": password,
        }
        user_ser = UserSerializers(data=user_info)
        if user_ser.is_valid():
            user = user_ser.save()
        else:
            return ResponseStatus().failed(message=user_ser.errors)
    # --- end ---
    # 校验密码
    # --- start ---
    if checkPassword(user, password):
        payload = {
            "username": username,
            "password": password,
            "create_time": time.time()
        }
        token = jwt_encode(payload)
    else:
        return ResponseStatus().failed(message="密码错误")
    # --- end ---
    return ResponseStatus().success(data=token, message="登录成功")


def app_login(request):
    """
    小程序授权
    """
    # 取参
    # --- start ---
    post_data = eval(request.body.decode())
    code = post_data.get("code")
    login_code = post_data.get("login_code")
    # --- end ---
    we_login = wx.WeChatLogin()
    res = we_login.get_user_phone_number(code)
    if res["errcode"] == 0:
        phone = res["phone_info"]["phoneNumber"]
        password = "wechat"
        # 验证用户是否存在
        try:
            user = TbMiniappUser.objects.get(username=phone)
        except TbMiniappUser.DoesNotExist:
            user_info = {
                "uid": uuid.uuid1().hex,
                "username": phone,
                "password": password,
                "phone": phone,
                "wallet_balance": 0
            }
            user_ser = UserSerializers(data=user_info)
            if user_ser.is_valid():
                user = user_ser.save()
            else:
                return ResponseStatus().failed(message=user_ser.errors)
        if checkPassword(user, password):
            payload = {
                "username": phone,
                "password": password,
                "create_time": time.time()
            }
            token = jwt_encode(payload)
        else:
            return ResponseStatus().failed(message="密码错误")
    else:
        return ResponseStatus().failed(data=res)
    # 保存用户的open_id
    if user.mini_openid is None:
        open_id = wx.WxPayApi().get_openid(code=login_code)
        user.mini_openid = open_id
        user.save()
    return ResponseStatus().success(message="登录成功", data=token)


class AppLoginView(View):
    def post(self, request):
        """
        小程序登录
        """
        post_data = eval(request.body.decode())
        token = director.LoginDirector().login(**post_data)
        return ResponseStatus().success(message="登录成功", data=token)


def static_view(requests, path):
    document_root = STATIC_ROOT
    """
    显示静态文件
    """
    try:
        response = serve(request=requests, path=path, document_root=document_root)
    except Exception as e:
        errlog.error(e)
        return HttpResponse("1")
    return response


def regeo_location(request, user: TbMiniappUser):
    """
    逆地理编码
    """
    query_data = request.GET.dict()
    gps_location = query_data.get("gps_location")
    result = requests.GaodeApi().regeo(gps_location)
    result_data = result["regeocode"]["formatted_address"]
    return ResponseStatus().success(data=result_data)


def upload_file(request, user: TbMiniappUser):
    """
    上传文件
    """
    # 取参
    files = request.FILES
    # 保存头像
    profile_photo = files["file"]
    profile_photo_name_list = profile_photo.name.split(".")
    profile_photo_name = uuid.uuid1().hex + "." + profile_photo_name_list[len(profile_photo_name_list) - 1]
    save_path = os.path.join(MEDIA_ROOT, profile_photo_name)
    with open(save_path, "wb") as f:
        for content in profile_photo.chunks():
            f.write(content)
    # 返回路径
    request_path = "/static/media/" + profile_photo_name
    return ResponseStatus().success(message="上传成功", data=request_path)


def send_message(request, user):
    """
    发送短信验证码
    """
    post_data = eval(request.body.decode())
    phonenumber = post_data.get("phonenumber")
    verify_code = str(random.randrange(1000, 9999))
    cache.set(phonenumber, verify_code, SESSION_COOKIE_AGE)
    Sample.main(phonenumber, verify_code)
    return ResponseStatus().success(message="短信发送成功")


def get_serve_time(request):
    now = datetime.datetime.now()
    return ResponseStatus().success(data=now)


def update_profile(request, user: TbMiniappUser):
    """
    更新头像
    """
    post_data = eval(request.body.decode())
    profile = post_data.get("profile")
    user.profile = profile
    user.save()
    user_ser = UserInfoSerializers(instance=user)
    return ResponseStatus().success(message="头像更新成功", data=user_ser.data)


def get_user_info(request, user: TbMiniappUser):
    """
    获取个人资料
    """
    user_ser = UserInfoSerializers(instance=user)
    return ResponseStatus().success(data=user_ser.data)
